package com.namlh.jpa.crud.dao;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.namlh.jpa.crud.domain.User;


public class UserDaoImpl implements UserDao {

	private EntityManager entityManager;
	
	public void setEm(EntityManager em) {
		this.entityManager = em;
	}

	public User findByUserId(String userId) {
		return entityManager.find(User.class, userId);
	}

	public User findByUserName(String userName) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<User> criteria = cb.createQuery(User.class);
        Root<User> user = criteria.from(User.class);

        /*
         * Swap criteria statements if you would like to try out type-safe criteria queries, a new
         * feature in JPA 2.0 criteria.select(member).orderBy(cb.asc(member.get(Member_.name)));
         */

        criteria.select(user).where(cb.equal(user.get("userName"), userName));
        return entityManager.createQuery(criteria).getSingleResult();
	}

	public Collection<User> findAllOrderedByName() {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<User> criteria = cb.createQuery(User.class);
        Root<User> user = criteria.from(User.class);

        /*
         * Swap criteria statements if you would like to try out type-safe criteria queries, a new
         * feature in JPA 2.0 criteria.select(member).orderBy(cb.asc(member.get(Member_.name)));
         */

        criteria.select(user).orderBy(cb.asc(user.get("userName")));
        return entityManager.createQuery(criteria).getResultList();
	}

	public void addUser(User user) {
		entityManager.persist(user);
        return;
	}

	public void editUser(User user) {
		// TODO Auto-generated method stub

	}

	public void deleteUser(User user) {
		// TODO Auto-generated method stub

	}

}
